package com.jack006.user.service.impl;

import com.jack006.enums.Sex;
import com.jack006.enums.UserStatus;
import com.jack006.exception.GraceException;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.AppUser;
import com.jack006.pojo.bo.UpdateUserInfoBO;
import com.jack006.user.mapper.AppUserMapper;
import com.jack006.user.service.UserService;
import com.jack006.utils.DateUtil;
import com.jack006.utils.DesensitizationUtil;
import com.jack006.utils.JsonUtils;
import com.jack006.utils.RedisOperator;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

/**
 * @Classname UserServiceImpl
 * @Description 用户接口实现
 * @Date 2021-06-13 16:59
 * @Created by jack
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private Sid sid;
    @Autowired
    private RedisOperator redisOperator;

    private static final String USER_FACE0 = "picture/face01.png";
    private static final String USER_FACE1 = "picture/face02.jpeg";
    private static final String USER_FACE2 = "picture/face03.jpeg";

    public static final String REDIS_USER_INFO = "redis_user_info";

    @Override
    public AppUser queryMobileIsExist(String mobile) {
        Example userExample = new Example(AppUser.class);
        Example.Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("mobile", mobile);
        return appUserMapper.selectOneByExample(userExample);
    }

    @Transactional
    @Override
    public AppUser createUser(String mobile) {

        /**
         * 互联网项目都需要考虑可扩展性
         * 如果未来的业务激增，那么就需要分库分表
         * 那么数据库表主键 id 必须保证全局（全库）唯一，不得重复
         */
        String userId = sid.nextShort();

        AppUser user = new AppUser();
        user.setId(userId);
        user.setMobile(mobile);
        user.setNickname("用户：" + DesensitizationUtil.commonDisplay(mobile));
        user.setFace(USER_FACE1);
        user.setBirthday(DateUtil.stringToDate("2000-01-01"));

        user.setSex(Sex.secret.type);
        user.setActiveStatus(UserStatus.INACTIVE.type);


        user.setTotalIncome(0);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        appUserMapper.insert(user);
        return user;
    }

    @Override
    public void updateUserInfo(UpdateUserInfoBO updateUserInfoBO) {

        String userId = updateUserInfoBO.getId();

        // 保证双写数据一致，先删除 redis 中数据，后更新数据库
        String userRedisInfoKey = REDIS_USER_INFO + ":" + userId;
        redisOperator.del(userRedisInfoKey);

        AppUser appUser = new AppUser();
        BeanUtils.copyProperties(updateUserInfoBO, appUser);

        appUser.setUpdatedTime(new Date());
        appUser.setActiveStatus(UserStatus.ACTIVE.type);

        int updateResult = appUserMapper.updateByPrimaryKeySelective(appUser);
        if (updateResult != 1) {
            GraceException.display(ResponseStatusEnum.USER_UPDATE_ERROR);
        }

        // 再次查询用户的最新信息，放入 redis
        appUser = getUserById(userId);
        redisOperator.set(userRedisInfoKey, JsonUtils.objectToJson(appUser));

        // 缓存双删策略
        try {
            Thread.sleep(100);
            redisOperator.del(userRedisInfoKey);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public AppUser getUserById(String userId) {
        return appUserMapper.selectByPrimaryKey(userId);
    }
}
